package com.wmx.thread.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**********************************
 * @author wmx
 * @date 2019/8/15 17:08
 * @description:
 * @version 1.0
 ************************************/
public class FutureTest{
    public static void main(String[] args) {
        FutureService futureService = new FutureService();
        Future future = futureService.display(() ->{
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return  "wumengixn";
        });
        System.out.println("去做其他事情=================");
        System.out.println(future.get());


    }

}

class FutureService{
    public <T> Future<T> display(final FutureTask<T> futureTask){
        SycFuture<T> sycFuture = new SycFuture<T>();
        new Thread(() ->{
            T result =  futureTask.call();
            sycFuture.done(result);
        }).start();

        return sycFuture;
    }
}


interface Future<T>{
    public T get();
}

class SycFuture<T> implements Future<T>{
    private    volatile  static  boolean done = false;
    private T result;

    public void done(T result){
      synchronized (this){
           this.done = true;
           this.result = result;
           this.notifyAll();
       }
    }

    @Override
    public T get() {
        synchronized (this){
            while (!done){
                try {

                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }
}

interface FutureTask<T> {
    public T call();
}

